package com.chl.tools;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.Ole10Native;
import org.apache.poi.poifs.filesystem.Ole10NativeException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.StringUtil;

/**
 * @Description office解析嵌入文件工具
 * @Author 李帅
 * @Date 2023/4/2 10:07
 * @Version 1.0
 **/
public class OfficeUtils {

	private final static String[] VIDEO_TYPE = { "mp4", "avi", "mkv", "mov", "wmv" };
	private final static String[] AUDIO_TYPE = { "mp3", "wav", "flac", "ogg", "aac" };
	public final static String VIDEO = "video";
	public final static String AUDIO = "audio";
	private final static String OTHER = "other";
	public final static String TEXT = "text";
	public final static String IMAGE = "image";

	/**
	 * 返回嵌入对象信息xlsx
	 * 
	 * @param i 输入流
	 * @return 后缀名和字节
	 */
	public static OfficeEmbed getEmbedInfo(InputStream i) {
		try (POIFSFileSystem fs = new POIFSFileSystem(i)) {
			Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject(fs.getRoot());
			String fileName = ole10.getLabel();
			String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
			byte[] b = ole10.getDataBuffer();
			if (StringUtil.isNotBlank(suffix)) {
				return new OfficeEmbed(getFileType(suffix.toLowerCase()), suffix, b);
			}
		} catch (Ole10NativeException | IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 返回嵌入对象信息xls
	 * 
	 * @param d 目录节点
	 * @return 后缀名和字节
	 */
	public static OfficeEmbed getEmbedInfo(DirectoryNode d) {
		try {
			
			Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject(d);
			String fileName = ole10.getLabel();
			String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
			byte[] b = ole10.getDataBuffer();
			if (StringUtil.isNotBlank(suffix)) {
				return new OfficeEmbed(getFileType(suffix.toLowerCase()), suffix, b);
			}
		} catch (Ole10NativeException | IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 判断嵌入文件格式
	 * 
	 * @param suffix 后缀
	 * @return 类型
	 */
	public static String getFileType(String suffix) {
		if (Arrays.asList(VIDEO_TYPE).contains(suffix)) {
			return VIDEO;
		}
		if (Arrays.asList(AUDIO_TYPE).contains(suffix)) {
			return AUDIO;
		}
		return OTHER;
	}
}
